package cn.est.service.impl;

import cn.est.config.AliSmsConfig;
import cn.est.constants.Constants;
import cn.est.service.SMSService;
import cn.est.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
@Slf4j
@EnableConfigurationProperties(AliSmsConfig.class)
public class SMSServiceImpl implements SMSService {
    @Autowired
    private AliSmsConfig aliSmsConfig;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean sendSMS(String phone, int codeType, Map<String, Object> map) {
        String templateParam = JSON.toJSONString(map);
        if (Constants.CodeType.LOGIN == codeType) { //注册 登录验证
//            String accessKeyId = "LTAI4FyRSnHQfrTkmrRAW7D5";
//            String accessSecret = "qyir4RNYcplvJCrDntdMq80G6xwxcD";
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliSmsConfig.getAccessKeyId(), aliSmsConfig.getAccessSecret());
            IAcsClient client = new DefaultAcsClient(profile);

            CommonRequest request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("RegionId", "cn-hangzhou");
            request.putQueryParameter("PhoneNumbers", phone);
            request.putQueryParameter("SignName", aliSmsConfig.getSignName());
            request.putQueryParameter("TemplateCode", aliSmsConfig.getTemplateCode());
            request.putQueryParameter("TemplateParam", templateParam);
            try {
                CommonResponse response = client.getCommonResponse(request);
                String responseData = response.getData();
                JSONObject jsonObject = JSON.parseObject(responseData);
                if ("OK".equals(jsonObject.get("Code"))) {
                    return true;
                }
                log.info("发送短信的结果:{}", responseData);
            } catch (ServerException e) {
                log.error("发送短信的结果:{}",e);
            } catch (ClientException e) {
                log.error("发送短信的结果:{}",e);
            }
        }
        return false;
    }

    @Override
    public void verifCode(String phone, int codeType) {
        //先检查是否生成验证码
        String verifCodeKey = Constants.LOGIN_VERIF_CODE_PREFIX + phone;
        String code = (String) redisUtil.get(verifCodeKey);
        //如果已经生成，直接返回
        if (code != null) {
            return;
        }
        //没有生成，就生成验证码
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(10));
        }
        code = stringBuilder.toString();
        //调用短信服务发送短信
        Map<String,Object> map = new HashMap<>();
        map.put("code",code);
        if (sendSMS(phone,codeType,map)) {
            log.info("手机号为:{},的验证码为:{}",phone,code);
            //把验证码记录在redis中，设置过期时间
            boolean set = redisUtil.set(verifCodeKey, code, 5 * 60);
            if (set) {
                log.info("验证码为:{},存入redis成功!",code);
            }
        }
    }
}
